﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using xTeam.Hengle.DataAccess;
using xTeam.HengLe.Enums;
using System.Globalization;
using xTeam.HengLe.DataAccess;
using System.Web.Mvc;
using ShopB2C.SQLDataAccess;
using System.Web.Security;
using ShopB2C.Entity;
using System.Web;
using System.Web.Script.Serialization;

namespace xTeam.HengLe.Controller {
    public partial class BaseController : System.Web.Mvc.Controller {
        protected string _connectionString, _langName;
        protected static ClassifyDataAccess _classifyDataAccess;
        protected static NewsDataAccess _newsDataAccess;
        protected static AdvertiseDataAccess _advertiseDataAccess;
        protected static ProductDataAccess _productDataAccess;
        protected static GuestBookDataAccess _guestBookDataAccess;
        protected static UserAccess _userAccess;
        protected static RolesAccess _rolesAccess;
        protected static ShopCarAccess _shopCarAccess;
        protected static OrderAccess _orderAccess;
        protected const string _imageRoot = "/ProductImages";

        public BaseController() {

        }

        protected override void Initialize(System.Web.Routing.RequestContext requestContext) {
            base.Initialize(requestContext);

            _langName = Session["Language"] != null ? Session["Language"].ToString() : "zh-cn";

            _connectionString = ConfigurationManager.ConnectionStrings["Data"].ConnectionString;
            _classifyDataAccess = new ClassifyDataAccess(_connectionString, _langName);
            _productDataAccess = new ProductDataAccess(_connectionString, _langName);
            _newsDataAccess = new NewsDataAccess(_connectionString, _langName);
            _advertiseDataAccess = new AdvertiseDataAccess(_connectionString, _langName);
            _guestBookDataAccess = new GuestBookDataAccess(_connectionString, _langName);
            _userAccess = new UserAccess(_connectionString);
            _shopCarAccess = new ShopCarAccess(_connectionString,_langName);
            _orderAccess = new OrderAccess(_connectionString,_langName);
            _rolesAccess = new RolesAccess(_connectionString);

            CultureInfo cultureInfo = new CultureInfo(_langName);
            System.Threading.Thread.CurrentThread.CurrentCulture = cultureInfo;
            System.Threading.Thread.CurrentThread.CurrentUICulture = cultureInfo;
            System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name);
            System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name);


            #region 站点地图

            if (ViewData["SiteMapPath"] != null) {
                ((List<string>)ViewData["SiteMapPath"]).Clear();
            }
            else {
                ViewData["SiteMapPath"] = new List<string>();
            }
            #endregion

        }
        public ActionResult ChangeCulture(string lang, string returnUrl) {
            string langName = lang != "" && lang != "en-us" && lang != "zh-cn" ? "zh-cn" : lang;
            this.Session["Language"] = langName;
            this.Session["Culture"] = new CultureInfo(langName);
            return this.Redirect("/");
        }
        /// <summary>
        /// 创建分页匿名对象
        /// </summary>
        /// <param name="HrefFormat">Url 格式字符串，
        /// 注意 UrlHelper 会将 {0} 转义，链接到字符串需要占用格式化字符串 {0} 占位符</param>
        /// <param name="pageSize">总页数</param>
        /// <param name="pageIndex">当前页码</param>
        /// <returns>分页匿名对象</returns>
        protected virtual object CreatePager(string HrefFormat, int pageCount, int pageIndex) {
            return new {
                PageIndex = pageIndex,
                PageCount = pageCount,

                FirstPageText = ViewsResources.Shared.PagerFirst,
                LastPageText = ViewsResources.Shared.PagerLast,

                PageDownText = ViewsResources.Shared.PagerNext,
                PageUpText = ViewsResources.Shared.PagerPrevious,

                HrefFormat = Server.UrlDecode(HrefFormat)
            };
        }

        /// <summary>
        /// 添加 SiteMapPath 路径
        /// </summary>
        /// <param name="url">路径</param>
        protected void SiteMapPathAdd(string linkText) {
            this.SiteMapPathAdd(linkText, null);
        }
        /// <summary>
        /// 添加 SiteMapPath 路径
        /// </summary>
        /// <param name="linkText">链接文字</param>
        /// <param name="url">路径</param>
        protected void SiteMapPathAdd(string linkText, string url) {
            List<string> urls = (List<string>)ViewData["SiteMapPath"];
            urls.Add(string.IsNullOrEmpty(url)
                ? linkText
                : string.Format("<a href=\"{0}\" target=\"_self\">{1}</a>", url, linkText));
            ViewData["SiteMapPath"] = urls;
        }
        /// <summary>
        /// 修改 SiteMapPath 路径
        /// </summary>
        /// <param name="oldLinkText">原链接文字</param>
        /// <param name="newLinkText">新链接文字</param>
        protected void SiteMapPathEdit(string oldLinkText, string newLinkText) {
            this.SiteMapPathEdit(oldLinkText, newLinkText, null);
        }
        /// <summary>
        /// 修改 SiteMapPath 路径
        /// </summary>
        /// <param name="oldLinkText">原链接文字</param>
        /// <param name="newLinkText">新链接文字</param>
        /// <param name="url">链接路径</param>
        protected void SiteMapPathEdit(string oldLinkText, string newLinkText, string url) {
            List<string> urls = (List<string>)ViewData["SiteMapPath"];
            int index = urls.FindIndex(s => { return s.Contains(oldLinkText); });
            if (index >= 0 && index < urls.Count) {
                urls[index] = string.IsNullOrEmpty(url)
                    ? newLinkText
                    : string.Format("<a href=\"{0}\" target=\"_self\">{1}</a>", url, newLinkText);
            }
            ViewData["SiteMapPath"] = urls;
        }
        /// <summary>
        /// 写入登录Cookie
        /// </summary>
        /// <param name="_user">关联的用户对象</param>
        /// <param name="timeOut">过期时间</param>
        protected internal void WriteLoginCookie(UserEntity user, int timeout) {
            // 序列化对象
            JavaScriptSerializer json = new JavaScriptSerializer();
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                1
                , user.NickName
                , DateTime.Now
                , DateTime.Now.AddYears(10)
                , true
                , json.Serialize(user)
                );

            string encTicket = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
            if (timeout > 0)
                cookie.Expires = DateTime.Now.AddMinutes(timeout);
            if (!string.IsNullOrEmpty(FormsAuthentication.CookieDomain))
                cookie.Domain = FormsAuthentication.CookieDomain;
            Response.Cookies.Add(cookie);
        }
    }
}
